package home

import (
	"hermestrans/basis/middleware"
	"hermestrans/internal/portal/auth"
	"hermestrans/internal/portal/config"
	mgr "hermestrans/internal/portal/manager"
	"hermestrans/internal/portal/schema"
	"net/http"
	"strings"
	"sync"

	"hermestrans/basis/utils"

	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
)

type HomeHandler struct {
	conf     *config.Config
	userAuth *auth.Auth
	mysqlMgr *mgr.MysqlMgr
	redisMgr *mgr.RedisMgr
}

var (
	homeInstance *HomeHandler
	handlerOnce  sync.Once
)

func NewHandler(conf *config.Config, mysqlMgr *mgr.MysqlMgr,
	redisCli *mgr.RedisMgr) *HomeHandler {
	handlerOnce.Do(func() {
		userAuth, _ := auth.NewAuth(mysqlMgr, redisCli)
		homeInstance = &HomeHandler{
			conf:     conf,
			userAuth: userAuth,
			mysqlMgr: mysqlMgr,
			redisMgr: redisCli,
		}
	})
	return homeInstance
}

func (home HomeHandler) Home(c *gin.Context) {
	username, ok := c.Get(utils.KeyUserName)
	if !ok {
		c.Header("Content-Type", "text/html; charset=utf-8")
		c.String(200, `<script type="text/javascript">top.location.href="/admin/login"</script>`)
		return
	}
	//先查下用户所在的组
	privs, err := home.userAuth.GetGroupByUser(username.(string))
	if err != nil {
		logrus.Error(err.Error(), "GetGroupByUser fail")
		return
	}
	groupname := strings.Join(privs, ",")
	uid, ok := c.Get(utils.KeyUid)
	if !ok {
		c.Header("Content-Type", "text/html; charset=utf-8")
		c.String(200, `<script type="text/javascript">top.location.href="/admin/login"</script>`)
		return
	}
	adminUser, _ := home.mysqlMgr.GetAdminUser(map[string]interface{}{utils.KeyUid: uid})
	middleware.Html(c, http.StatusOK, "home/home.html", gin.H{
		"groupName": groupname,
		"header":    adminUser.Header,
		"logo":      adminUser.Logo,
		"sider":     adminUser.Side,
	})
}

func (home HomeHandler) Welcome(c *gin.Context) {
	middleware.Html(c, http.StatusOK, "home/welcome.html", gin.H{})
}

func (home HomeHandler) EditPassword(c *gin.Context) {
	id := c.Query("id")
	middleware.Html(c, http.StatusOK, "home/password_form.html", gin.H{
		"id": id,
	})
}

/**
*	修改密码
 */
func (home HomeHandler) SavePassword(c *gin.Context) {
	var (
		req schema.AdminUserEditPassReq
	)
	middleware.FormBind(c, &req)

}
